package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.HttpUtils
import top.kikt.book.util.HttpUtils.string
import java.nio.charset.Charset

/**
 * http://www.bookxuan.com
 */
class BookXuan : BaseBookHandler() {

    override val host: String
        get() = "www.bookxuan.com"

    override val hosts: List<String>
        get() = listOf("www.bookxuan.com", "bookxuan.org")

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.getElementsByTag("h1")[0].text()
        val infoDiv = document.getElementById("info")!!
        val authorP = infoDiv.getElementsByTag("p")[0]
        val author = authorP.text()

        val cover = document.select("#fmimg > script").first()?.let {
            val scriptSrc = it.attr("src")
            val srcUrl = url.toHttpUrl().resolve(scriptSrc).toString()

            logger.info("获取 $srcUrl")

            val script = HttpUtils.get(srcUrl).string(Charset.forName("gbk")) ?: return@let null

            // document.writeln("<img alt='' src='https://www.bookxuan.org/files/article/image/13/13127/13127s.jpg' width='120' height='150' />")

            val src = Regex("src='(.*?)'").find(script)?.groupValues?.get(1)
            src?.let { notnullUrl ->
                url.toHttpUrl().resolve(notnullUrl).toString()
            }
        }

        logger.info("name: $name, author: $author, cover: $cover")

        return BookMetaEntity(name, url, url, author, cover)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val arrayList = ArrayList<ChapterMetaEntity>()

        val dl = document.getElementsByTag("dl")[0]

        var start = false

        var index = 0

        for (child in dl.children()) {
            if (!start) {
                if (child.text().contains("正文")) {
                    start = true
                    continue
                }
                continue
            }

            val aElement = child.getElementsByTag("a")
            val href = aElement.attr("href")

            menuUrl.toHttpUrl().resolve(href)

//            val targetUrl = "$scheme://${URL(menuUrl).host}$href"
            val targetUrl = menuUrl.toHttpUrl().resolve(href)?.toString() ?: continue
            val title = aElement.text().trim()

            index++
            val chapterMeta = ChapterMetaEntity(title, index, targetUrl, child)

            arrayList.add(chapterMeta)
        }

        return arrayList
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val name = "第${chapterMetaEntity.index}章 ${chapterMetaEntity.name}"

        val doc = HttpUtils.get(chapterMetaEntity.url).string(forceCharset())?.toDocument() ?: return null

        val content = doc.getElementById("content")!!

        return ChapterEntity(name, chapterMetaEntity.index, content.wholeText())
    }

    override fun forceCharset(): Charset {
        return Charset.forName("gbk")
    }
}